<style>
.z-plumb-container {
  position: relative;
}
.z-plumb-dep {
  width: 300px;
  border: 1px solid #eee;
  position: absolute;
  background-color: #e3efef;
}
.z-plumb-dep__item {
  padding: 10px;
  box-sizing: border-box;
}
</style>

<template>
  <div class="z-plumb-container-con">

    <div :id="containerId" class="z-plumb-container">
      <div :id="dep.id" class="z-plumb-dep" v-for="dep in deps" :key="dep.id">
        <div class="z-plumb-dep__header"
             :data-pid="dep.id"
             :id="DEP_ID(dep, 'top')">
          header
        </div>
        <div class="z-plumb-dep__body">
          <div class="z-plumb-dep__item" :id="item.id" v-for="item in dep.items" :key="item.id">
            <slot name="dep_item" v-bind="{item, dep}"></slot>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>

import {createPlumbConfig} from "./utils";

let COMMON_MIXIN = {
  data() {
    return {
      pointsMap: {},
      posMap: {}
    }
  },
  methods: {
    makeDraggable(id, instance) {
      let self = this
      instance.draggable(id, {
        stop: function(event, ui) {
          // Your code
          // console.log('sdsdsds', event.finalPos)
          self.posMap[id] = {
            pos: event.finalPos
          }
        }
      })
    },
    addEndpoint(itemId, options, depId, suffix = '') {
      let self = this;
      let config = this.config;
      if (document.getElementById(itemId)) {
        let endpoint = self.instance.addEndpoint(itemId , options, config.baseStyle);
        // // console.log(endpoint)
        ZY.lodash.set(self.pointsMap, [depId, itemId + suffix], endpoint)
        // self.instance.makeSource(itemId, options, config.baseStyle)
      }
    },
    addItemEndPoints(itemId, depId) {
      this.addEndpoint(itemId, {
        anchors: ['Left']
      }, depId, 'Left')

      // this.addEndpoint(itemId, {
      //   anchors: ['Right']
      // }, depId, 'Right')
    },
  }
}

export default {
  name: 'ZPlumbContainer',
  mixins: [
    COMMON_MIXIN
  ],
  data() {
    return {
      containerId: 'con__' + ZY.rid(),
      instance: null,
      deps: [],
      config: {},
      STORE_NAME: 'store_111'
    }
  },
  async beforeCreate() {
    let self = this;
    let obj =  await ZY_EXT.store.getItem(this.STORE_NAME)
    if (obj) {
      ZY.lodash.each(obj, function (item, key) {
        self[key] = item[key]
      })
    }
  },
  mounted() {
    let self = this;
    self.config = createPlumbConfig(self)
    let container = document.getElementById(this.containerId);
    window.jsPlumb.ready(async function () {

      await self.store__get();
      self.instance = window.jsPlumb.getInstance({
        Container: container
      });
      window.__jsplumb_instance__ = self.instance;
      await  ZY.sleep(300)
      self.init();
      // if (self.deps.length < 1) {
      //   let id1 = ZY.rid();
      //   let id2 = ZY.rid();
      //   self.deps = [
      //     {
      //       id: id1,
      //       name: 'dep__' + id1
      //     },
      //     {
      //       id: id2,
      //       name: 'dep__' + id2
      //     },
      //   ]
      //   self.appendItem(self.deps[0])
      //   self.appendItem(self.deps[0])
      //   self.appendItem(self.deps[1])
      //   setTimeout(() => {
      //     self.store__set()
      //   }, 300)
      // }
    })
  },

  methods: {
    init() {
      let self = this
      self.deps.forEach(dep => {
        self.makeDraggable(dep.id, self.instance);
        self.restoreDep(dep)
      })
    },
    DEP_ID(dep, key) {
      return dep.id + '-' + key
    },
    async appendItem(dep, data = {}) {
      if (!dep.items) {
        this.$set(dep, 'items', [])
      }
      let newItem = {
        id: dep.id + '__' + ZY.rid(),
        name: dep.id + '__item__' + ZY.rid(3),
        ...data
      }
      dep.items.push(newItem);
      await this.$nextTick();
      this.addItemEndPoints(newItem.id, dep.id)
    },

    // 恢复dep
    restoreDep(dep) {
      if (Array.isArray(dep.items)) {
        dep.items.forEach(item => {
          this.addItemEndPoints(item.id, dep.id)
        })
      }
    },

    async store__get() {
      let self = this;
      let obj =  await ZY_EXT.store.getItem(this.STORE_NAME)
      if (obj) {
        ZY.lodash.each(obj, function (item, key) {
          self.$set(self, key, item)
        })
      }
    },
    async store__set() {
      const {toRaw} = vueCompositionAPI
      let obj = ZY.lodash.cloneDeep({
        deps: toRaw(this.deps),
        // pointsMap: this.pointsMap,
        posMap: this.posMap
      })
      // console.log(obj)
      ZY_EXT.store.setItem(this.STORE_NAME, obj)
    }
  }
}
</script>
